package com.bitdf.txing.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bitdf.txing.product.dao.CategoryDao;
import com.bitdf.txing.product.entity.CategoryEntity;
import com.bitdf.txing.product.service.CategoryBrandRelationService;
import com.bitdf.txing.product.service.CategoryService;
import com.bitdf.txing.product.vo.Catalogs2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;
//    @Autowired
//    private JedisPool jedisPool;

//    @Override
//    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<CategoryEntity> page = this.page(
//                new Query<CategoryEntity>().getPage(params),
//                new QueryWrapper<CategoryEntity>()
//        );
//
//        return new PageUtils(page);
//    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            // TODO 改了
            return categoryEntity.getParentCid().equals(root.getId());
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //ToDo 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

//    @Override
//    public Long[] findCatelogPath(Long catelogId) {
//        List<Long> paths=new ArrayList<>();
//        List<Long> parentPath=findParentPath(catelogId,paths);
//        Collections.reverse(parentPath);
//        return parentPath.toArray(new Long[parentPath.size()]);
//    }
//
//    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
//        paths.add(catelogId);
//        CategoryEntity byId=this.getById(catelogId);
//        if(byId.getParentCid()!=0)
//        {
//            findParentPath(byId.getParentCid(),paths);
//        }
//        return paths;
//    }


    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    //    @CacheEvict(value = "category",key = "'getLevel1Categorys'")
//    @CacheEvict(value = "category",allEntries = true)
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category", key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        // TODO 改了
        categoryBrandRelationService.updateCategory(category.getId(), category.getName());

    }


    /**
     * 获取商品一级分类
     *
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

//    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catalogs2Vo>> getCatalogJson() {
//        Jedis jedis = jedisPool.getResource();
//        String str = "";
//        if ((str = jedis.get("category")) != null) {
//            return JSON.parseObject(str, new TypeReference<Map<String, List<Catalogs2Vo>>>(){});
//        }
        String str = "";
        if ((str = redisTemplate.opsForValue().get("category")) != null) {
            return JSON.parseObject(str, new TypeReference<Map<String, List<Catalogs2Vo>>>(){});
        }
        /**
         * 优化:将数据库中的多次查询变为一次,存至缓存selectList,需要的数据从list取出,避免频繁的数据库交互
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查出所有1级分类
        List<CategoryEntity> level1 = getParentCid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catalogs2Vo>> parent_cid = level1.stream().collect(Collectors.toMap(k -> k.getId().toString(), v -> {
                    //1.查出1级分类中所有2级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getId());
                    //2.封装上面的结果
                    List<Catalogs2Vo> Catalogs2Vos = null;
                    if (categoryEntities != null) {
                        Catalogs2Vos = categoryEntities.stream().map(l2 -> {
                            Catalogs2Vo Catalogs2Vo = new Catalogs2Vo(v.getId().toString(), null, l2.getId().toString(), l2.getName());
                            //查询当前2级分类的3级分类
                            List<CategoryEntity> level3 = getParentCid(selectList, l2.getId());
                            if (level3 != null) {
                                List<Catalogs2Vo.Catagory3Vo> collect = level3.stream().map(l3 -> {
                                    //封装指定格式
                                    Catalogs2Vo.Catagory3Vo catelog3Vo = new Catalogs2Vo.Catagory3Vo(l2.getId().toString(), l3.getId().toString(), l3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                Catalogs2Vo.setCatalog3List(collect);
                            }
                            return Catalogs2Vo;
                        }).collect(Collectors.toList());
                    }
                    return Catalogs2Vos;
                }
        ));
//        String s = JSON.toJSONString(parent_cid);
//        jedis.set("category", s);
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("category", s);
        return parent_cid;
    }


    /**
     * 加缓存前,只读取数据库的操作
     *
     * @return
     */
    public Map<String, List<Catalogs2Vo>> getCatalogJsonFromDB() {
        System.out.println("查询了数据库");

        // 性能优化：将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categories = getParentCid(selectList, 0L);

        //封装数据
        Map<String, List<Catalogs2Vo>> parentCid = level1Categories.stream().collect(Collectors.toMap(k -> k.getId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getId());

            //2、封装上面的结果
            List<Catalogs2Vo> catalogs2Vos = null;
            if (categoryEntities != null) {
                catalogs2Vos = categoryEntities.stream().map(l2 -> {
                    Catalogs2Vo catalogs2Vo = new Catalogs2Vo(v.getId().toString(), null, l2.getId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getId());

                    if (level3Catelog != null) {
                        List<Catalogs2Vo.Catagory3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catalogs2Vo.Catagory3Vo category3Vo = new Catalogs2Vo.Catagory3Vo(l2.getId().toString(), l3.getId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catalogs2Vo.setCatalog3List(category3Vos);
                    }

                    return catalogs2Vo;
                }).collect(Collectors.toList());
            }

            return catalogs2Vos;
        }));

        return parentCid;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        return selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }


    public Map<String, List<Catalogs2Vo>> getCatelogJson2() {
        //加入缓存逻辑,缓存中存的数据是JSON字符串
        //JSON跨语言,跨平台兼容
        //从缓存中取出的数据要逆转为能用的对象类型,序列化与发序列化
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存中没有数据,查询数据库
            Map<String, List<Catalogs2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedissonLock();
            //查到的数据再放入缓存,将对象转为JSON放入缓存中
            String s = JSON.toJSONString(catelogJsonFromDb);
            redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
            return catelogJsonFromDb;
        }
        Map<String, List<Catalogs2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalogs2Vo>>>() {
        });
        return result;
    }


    private Map<String, List<Catalogs2Vo>> getDataFromDB() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catalogs2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalogs2Vo>>>() {
            });
            return result;
        }
        /**
         * 优化:将数据库中的多次查询变为一次,存至缓存selectList,需要的数据从list取出,避免频繁的数据库交互
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查出所有1级分类
        List<CategoryEntity> level1 = getParentCid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catalogs2Vo>> parent_cid = level1.stream().collect(Collectors.toMap(k -> k.getId().toString(), v -> {
                    //1.查出1级分类中所有2级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getId());
                    //2.封装上面的结果
                    List<Catalogs2Vo> Catalogs2Vos = null;
                    if (categoryEntities != null) {
                        Catalogs2Vos = categoryEntities.stream().map(l2 -> {
                            Catalogs2Vo Catalogs2Vo = new Catalogs2Vo(v.getId().toString(), null, l2.getId().toString(), l2.getName());
                            //查询当前2级分类的3级分类
                            List<CategoryEntity> level3 = getParentCid(selectList, l2.getId());
                            if (level3 != null) {
                                List<Catalogs2Vo.Catagory3Vo> collect = level3.stream().map(l3 -> {
                                    //封装指定格式
                                    Catalogs2Vo.Catagory3Vo catelog3Vo = new Catalogs2Vo.Catagory3Vo(l2.getId().toString(), l3.getId().toString(), l3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                Catalogs2Vo.setCatalog3List(collect);
                            }
                            return Catalogs2Vo;
                        }).collect(Collectors.toList());
                    }
                    return Catalogs2Vos;
                }
        ));
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }

    //分布式锁Redisson
    public Map<String, List<Catalogs2Vo>> getCatelogJsonFromDbWithRedissonLock() {
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        //加锁成功,执行业务
        Map<String, List<Catalogs2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }
}